﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace DataSyncApp
{
    public class Help
    {
        /// <summary>
        /// API发送POST请求
        /// </summary>
        /// <param name="url">请求的API地址</param>
        /// <param name="parametersJson">POST过去的参数（JSON格式）字符串</param>
        /// <returns></returns>
        public string ApiPost(string url, string parametersJson)
        {
            try
            {
                HttpClient client = new HttpClient();
                // 为JSON格式添加一个Accept报头
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //需要传递的参数（参数封装成JSON）
                HttpContent content = new StringContent(parametersJson)
                {
                    Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
                };

                HttpResponseMessage response = client.PostAsync(url, content).Result;
                response.EnsureSuccessStatusCode();
                return response.Content.ReadAsStringAsync().Result;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// API发送GET请求，返回Json
        /// </summary>
        /// <param name="url"></param>
        /// <returns>如果未成功返回空</returns>
        public string ApiGet(string url)
        {
            try
            {
                HttpClient client = new HttpClient();
                // 为JSON格式添加一个Accept报头
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)
                {
                    return response.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// 将JSON解析为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public T JsonToObject<T>(string data) where T : class
        {
            try
            {
                var person = JsonConvert.DeserializeObject<T>(data);
                return person;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}